<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class user_model extends CI_Model {

	/**
	*
	* The login method will create a session storing the users information if the email and password match
	* a record within the 'user' table.  If the pair is not found then this will return FALSE.
	*
	* @name	login
	* @param	array	$data	This is the data within the $_POST variable containing the username and password
	* @return	array	$user	This will return the user's record within an array on success or FALSE on failure
	*
	*/
	public function login($data = array())
	{
		$params = array('email' => strtolower($data['username']), 'password' => crypt($data['password'], $this->config->item('encryption_key')));
		$query = $this->db->get_where('user', $params);

		if ($query->num_rows() == 1)
		{
			$user = $query->row();
			$this->session->set_userdata('user', $user);
			return $user;  // Success
		}

		return FALSE; // Failed
	}
 
     /**
     * 
     * Register will verify the email does not already exist and then will create an entry in the 'new_user' table
     * 
     * @name        register
     * @param       array   $post_var       This will contain the data within the $_POST variable which includes the email and password
     * @return      array                           This will return an array containing both the email address and the newly created access code
     * 
     */
    public function register($post_var)
    {
        $this->load->helper('string');
        $rand = random_string('unique'); //  Create a randomly generated access code
        
        $params = array(
            'email' => strtolower($post_var['email']),
            'password' => crypt($post_var['password'], $this->config->item('encryption_key')),
            'verify_code' => $rand
        );
        
        if ($this->check_email($post_var['email'])) //  Check to ensure the email does not already exist and is a college email address
        {
            $this->db->insert('new_user', $params);
            
            if ($this->db->affected_rows() == 1)
            {
                return array('email' => $post_var['email'], 'verify_code' => $rand);
            }
        }
        
        return FALSE;
    }

     /**
     * 
     * Check_Email is a helper function used to validate the email does not already exist and is a valid school email ending in .edu
     * 
     * @name        check_email
     * @param       string          $email          This is the email address to be validated
     * @return      bool                                    Will return TRUE if validation was successful or FALSE if it was not successful
     * 
     */
    public function check_email($email)
    {
        if (substr($email, -4, 4) != '.edu') //  Verify the email ends in .edu
        {
            $this->session->set_flashdata('register_error', '<p class="error">Please use your school email address ending in ".edu" to register.</p>');
            return FALSE;
        }
        
        $query1 = $this->db->get_where('new_user', array('email' => strtolower($email))); //  Check to see if email exists in the 'new_user' table
        $query2 = $this->db->get_where('user', array('email' => strtolower($email))); //  Check to see if the email exists in the user table
        
        if ($query1->num_rows() > 0 || $query2->num_rows() > 0) //  If the email was found in either of the table return an error
        {
            $this->session->set_flashdata('register_error', '<p class="error">This email has already been registered.</p>');
            return FALSE;
        }
        
        return TRUE;
    }
    public function add_new_user($data)
    {
        $this->db->where('user_id', $data['user_id']);
        $this->db->update('user', $data);
        return FALSE; // Success
    }
    
     /**
     * 
     * remove_new_user will compare the provided access code against the record within the 'new_user' table.
     * If the pair is matched it will remove the record from the new user table.
     * 
     * @name        remove_new_user
     * @param       string          $code   This is the user provided access code to validate against the record
     * @return      bool                            This will return TRUE on success or FALSE on failure
     * 
     */
    public function remove_new_user($code)
    {
        $query = $this->db->get_where('new_user', array('verify_code' => $code));
                                
        if ($query->num_rows() == 1)
            $this->db->delete('new_user', array('verify_code' => $code));
    }
    
     /**
     * 
     * Check_Access_Code will compare the provided email and access code against the record within the 'new_user' table.
     * If the pair is matched it will move the record from the 'new_user' table and into the 'user' table.  If the pair
     * is not matched, it will return FALSE.
     * 
     * @name        check_access_code
     * @param       string          $email  This is the user provided email address used to look up the record within the 'new_user' table
     * @param       string          $code   This is the user provided access code to validate against the record
     * @return      bool                            This will return TRUE on success or FALSE on failure
     * 
     */
    public function check_access_code($code)
    {
        $query = $this->db->get_where('new_user', array('verify_code' => $code));
                                
        if ($query->num_rows() > 0)
        {
            $result = $query->row();
            //  By default this will create a user with a site_role of student
            $this->db->insert('user', array('email' => $result->email, 'password' => $result->password, 'site_role' => 'student'));
            
            if ($this->db->affected_rows() == 1) //  If the user was successfully moved into the 'user' table
            {
                if ($user = $this->db->get_where('user', array('user_id' => $this->db->insert_id())))
                {
                    $this->db->delete('new_user', array('email' => $result->email)); //  Remove the record in the 'new_user' table
                    return $user->row();
                }               
            }
        }
        
        return FALSE;
    }

    public function get_user($code)
    {
        $query = $this->db->get_where('new_user', array('verify_code' => $code));
                                
        if ($query->num_rows() <= 0)
            return FALSE;

        return $query->row_array();
    }

     public function get_user_details($userID) {
        $this->db->select('
            user.user_id,
            user.first_name,
            user.middle_name,
            user.last_name,
            user.prefix,
            user.suffix,
            user.college,
            user.school,
            user.major,
            user.minor,
            user.graduation_year,
            user.school_status,
            user.gpa,
            user.bio,
            user.department,
            user.co_department,
            user.user_score,
            college.college_id,
            college.college_name,
            school.school_id,
            school.school_name,
            major.major_id,
            major.major_name,
            minor.minor_id,
            minor.minor_name
        ');

        $this->db->join('college', 'college.college_id = user.college');
        $this->db->join('school', 'school.school_id = user.school');
        $this->db->join('major', 'major.major_id = user.major');
        $this->db->join('minor', 'minor.minor_id = user.minor');
        $query = $this->db->get_where('user', array('user.user_id' => $userID));

        if ($query->num_rows() != 1) return FALSE;
        return $query->row_array();
    }
}